$(document).ready(function() { 
	/****
	 * JQgrid根据屏幕分辨率 自适应
	 * 以下函数原理：根据父元素的大小自适应
	 * ********/	
  var resetJqgrid = function(){
      $(window).unbind("onresize"); 
      $("#prdInfoGrd").setGridWidth($("#prdInfoDiv").width()*0.95); 
      $("#prdInfoGrd").setGridHeight($("#prdInfoDiv").height()*0.80);     
      $("#crrInfoGrd ").setGridWidth($("#crrInfoDiv").width()*0.95); 
      $("#crrInfoGrd ").setGridHeight($("#crrInfoDiv").height()*0.80); 
      $(window).bind("onresize", this);  
  }
  var initializationFunc = function(){
    resetJqgrid();
    $("#venSlotNoSel").empty();
    //TODO:子格位号，怎样获取
    for(var i=26;i>0;i--){
    	$("#venSlotNoSel").append("<option value=>" + i + "</option>");
    }
    $("#slotNoSel").empty();
    for(var i=26;i>0;i--){
    	$("#slotNoSel").append("<option value=>" + i + "</option>");
    }
    $("#slotNoSel").select2({
    	theme : "bootstrap"
    });
  }
 
  /**
   * Reset size of jqgrid when window resize
   * @param  {[type]} )
   * @param  {[type]} this);
   * @return {[type]}
   */
  $(window).resize(function(){   

        window.location.reload();
      $(window).unbind("onresize"); 
      
      $("#prdInfoGrd").setGridWidth($("#prdInfoDiv").width()*0.95); 
      $("#prdInfoGrd").setGridHeight($("#prdInfoDiv").height()*0.80);     
      
      $("#crrInfoGrd ").setGridWidth($("#crrInfoDiv").width()*0.95); 
      $("#crrInfoGrd ").setGridHeight($("#crrInfoDiv").height()*0.80); 
      // alert("crrInfoGrd width"+ $("#crrInfoGrd").width() + "crrInfoDiv.width"+$("#crrInfoDiv").width()+
      //   "prdInfoGrd width"+ $("#prdInfoGrd").width() + "prdINfoDiv.width"+$("#prdInfoDiv").width()
      // );    
      
      $(window).bind("onresize", this);  
  });


  initializationFunc();

  var prdInfoCM = [
                  {name: 'ppbox_id',          index: 'ppbox_id',          label: PPBOX_ID_TAG,       width: 110},
                  {name: 'ppbox_slot',        index: 'ppbox_slot',        label: PPBOX_SLOT_NO_TAG,       width: 80 },
                  {name: 'prod_seq_id',       index: 'prod_seq_id',       label: PRD_SEQ_ID_TAG,         width: 117}
            ];
  $("#prdInfoGrd").jqGrid({
      url:"",
      datatype:"local",
      mtype:"POST",
      // height:"100%",
      // width:"99%",
      autowidth:true,//宽度根据父元素自适应
      shrinkToFit:true,
      scroll:true,
      rownumbers  :true ,
      rownumWidth : 20,
      resizable : true,
      rowNum:40,
      loadonce:true,
      fixed:true,
      viewrecords:true,
      pager : 'prdInfoPg',
      fixed: true,
     colModel: prdInfoCM  
  })
  var crrInfoCM = [
                  {name: 'crr_id',          index: 'crr_id',          label: CRR_ID_TAG,      width: 120},
                  {name: 'qty',             index: 'qty',             label: TOTAL_QTY_TAG,   width: 50 },
                  {name: 'stb_qty',         index: 'stb_qty',         label: STB_QTY_TAG,     width: 120}
            ];
  $("#crrInfoGrd").jqGrid({
      url:"",
      datatype:"local",
      mtype:"POST",
      // height:"100%",
      // width:"99%",
      autowidth:true,//宽度根据父元素自适应
      shrinkToFit:true,
      scroll:true,
      rownumbers  :true ,
      rownumWidth : 20,
      resizable : true,
      rowNum:40,
      loadonce:true,
      fixed:true,
      viewrecords:true,
      pager : 'crrInfoPg',
      fixed: true,
     colModel: crrInfoCM  
  })  
  /***就的JQuery dialog方式 弹出*******************/
//  $("#bayAreaSel").click(function(){
//	  var bay_id = $("#bayAreaSel").find("option:selected").text();
//	  $("#bayAreaSel").selectBayIDUnion({
//		  callbackFn : function(data) {
//	          $("#bayAreaSel").empty();
//	          $("#eqptIdSel").empty();
//	          $("#bayAreaSel").append("<option value=>" + data.bayID + "</option>");
//	          $("#eqptIdSel").append("<option value=>" + data.eqptID + "</option>");
//	          
//	  	  }
//	  })
//  })
  /***新的bootStrap Modal方式弹出*******************/
  $("#bayAreaSel").click(function(){
	  $("#bayAreaSel").showSelectBayToolDialog({
		  callbackFn : function(data) {
	          $("#bayAreaSel").empty();
	          $("#eqptIdSel").empty();
	          $("#bayAreaSel").append("<option value=>" + data.bayID + "</option>");
	          $("#eqptIdSel").append("<option value=>" + data.toolID + "</option>");
	          $("#bayAreaSel").select2({
	          	theme : "bootstrap"
	          });
	          $("#eqptIdSel").select2({
	          	theme : "bootstrap"
	          });
	  	  }
	  })
  })
   var f1_func = function(woder_id) {
    var inTrxObj ;
    if( woder_id==null){
        inTrxObj = {
          trx_id: 'XPINQWOR',
          action_flg: 'I',
          worder_id: $("#wordId2Spn").text()
      };
    }else{
        inTrxObj = {
          trx_id: 'XPINQWOR',
          action_flg: 'I',
          worder_id: woder_id
        }
    }
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if(outTrxObj.rtn_code == "0000000") {
    //        setGridInfo(outTrxObj,"#WOInforGrd");
        $("#wordId2Spn").text(outTrxObj.wo_id);
        $("#wordDsc2Spn").text(outTrxObj.wo_dsc);
        $("#wordCate2Spn").text(outTrxObj.wo_cate);
        $("#planSTBQty2Spn").text(outTrxObj.pln_prd_qty);
        $("#aleadySTBQty2Spn").text(outTrxObj.rl_prd_qty);
        $("#storageQty2Spn").text(outTrxObj.wh_in_prd_qty);
        $("#scrapQty2Spn").text(outTrxObj.scrp_prd_qty);
        $("#destShop2Spn").text(outTrxObj.dest_shop);
        $("#priority2Spn").text(outTrxObj.wo_prty);
        $("#route2Spn").text(outTrxObj.path_id_fk);
        $("#routeVer2Spn").text(outTrxObj.path_ver_fk);
        $("#startOpe2Spn").text(outTrxObj.str_ope_no);
        
      }
    }

  /***
      显示Layout
  ***/
  function layoutTdClickFnc(obj){
    if($(obj).hasClass("btn-success")){
      $(obj).removeClass("btn-success")
    }else{
      $(obj).addClass("btn-success");
    }
  }
  function showLayoutFnc(){
      //TODO:此处需要更改 
      var inTrxObj = {
          trx_id: 'XLAYOUTK',
          action_flg: 'I',
          prd_seq_id: 'xinworkid001'
      };
      var outTrxObj = comTrxSubSendPostJson(inTrxObj);
      if( outTrxObj.rtn_code == "0000000") {
          var enter_flg = true;
          var x_axis_cnt = comParseInt(outTrxObj.x_axis_cnt);
          var y_axis_cnt = comParseInt(outTrxObj.y_axis_cnt);
          var k;
          var index;
          var pos_location = 0;
          $("#layoutDiv").empty();
          var str = '<table class="table table-bordered table-condensed">'
          for( var i=0;i<y_axis_cnt;i++){
               str = str + '<tr>';
               for(var j=0;j<x_axis_cnt;j++){
               str = str +'<td id=layoutTd_'+ pos_location +' >' +
                     outTrxObj.oary[pos_location].pos_id + '</td>';
               if(j==x_axis_cnt-1){
                  str = str + '</tr>' ;
               }
                pos_location = pos_location+1;
            }
          }
          str = str +'</table>';
      
          $(str).appendTo($("#layoutDiv"));
          for(var i=0;i<pos_location;i++){
            $("#layoutTd_"+i).click(function(){
              layoutTdClickFnc(this);
            });
          }
        
      }  
  }
  /***显示Defect*****/
  function defectTdClickFnc(obj){
    // alert($(obj).text());
    if( $(obj).hasClass("btn-primary")){
        $(obj).removeClass("btn-primary")
    }else{
        $(obj).addClass("btn-primary");
    }
  }
  function showDefectFnc(){
    //Get Defect Info 
    var inTrxObj = {
          trx_id: 'XPINQCOD',
          action_flg: 'I',
          data_cate : 'DFCT',
          data_id   : '0000' //站点代码
    }
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if( outTrxObj.rtn_code == "0000000") {
        var enter_flg = true;
        var tbl_cnt = outTrxObj.tbl_cnt;
        $("#defectDiv").empty();
        var str = '<table class="table table-bordered table-condensed">'
        str = str + '<tr>';
        for(var i=1;i<=tbl_cnt;i++){
            str = str +'<td id=defectTd_'+i+' >'+ outTrxObj.oary[i-1].data_item +'</td>';
            if(i%4==0){
              str = str +'</tr><tr>'
            }
        }
        //如果不足4的倍数，补充空白
        if(tbl_cnt%4!=0){
          for(var i=0;i<4;i++){
            str = str +'<td></td>'; 
            if((tbl_cnt+i)%4==0){
              break;
            }
          }
        }
        str = str +'</tr></table>'

        $(str).appendTo($("#defectDiv"));
        for(var i=1;i<=tbl_cnt;i++){
          $("#defectTd_"+i).click(function(){
            defectTdClickFnc(this);
          });
        }
    }
  }
   function f5_func(){
    var rowCnt = $("#prdInfoGrd").jqGrid("getGridParam","reccount");
    var rowID  = rowCnt + 1 ;
    
    var vendorSlotIndex = $("#venSlotNoSel").get(0).selectedIndex;
    var slotNoIndex     = $("#slotNoSel").get(0).selectedIndex;
    
    var addRowData = {
        ppbox_id    : $("#ppboxIdTxt").val() ,
        ppbox_slot  : $("#venSlotNoSel").find("option:selected").text(),
        prod_seq_id : $("#prdSeqIdTxt").val()
    }
    $("#prdInfoGrd").jqGrid("addRowData",rowID,addRowData);//添加一行
    
    $("#venSlotNoSel").get(0).selectedIndex = vendorSlotIndex+1 ; 
    $("#slotNoSel").get(0).selectedIndex = slotNoIndex+1 ; 
    $("#prdSeqIdTxt").val("");
    $("#layoutDiv").empty();
    showLayoutFnc();
    showDefectFnc();
  }

  function f8_func(){
	  var inTrxObj = {
        trx_id  : 'XPSIQCIN',
        //biz_flg : 'A',
        action_flg : "A",
        evt_usr: 'Lin',
        // evt_timestamp : '2013-02-25 09:53:48',
        wo_id   : $("#wordId2Spn").text(),
        bay_id  : $("#bayAreaSel").find('option:selected').text(),
        so_id   : $("#wordId2Spn").text(),
        mtrl_box_id : $("#ppboxIdTxt").val(),
        mtrl_slot_no: $("#venSlotNoSel").find('option:selected').text(),
        prd_seq_id  : $("#prdSeqIdTxt").val(),
		    box_id      : $("#crrIdSel").val(),
		    slot_no     : $("#slotNoSel").find('option:selected').text() 
        //TODO:判定Defect功能还未添加
//				defect_cnt  : 0 , //TODO
//				defect_iary : null //TODO
	  };
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if( outTrxObj.rtn_code == "0000000") {
        showSuccessDialog();
    }else{
      showErrorDialog(outTrxObj.rtn_code,outTrxObj.rtn_msg);
    }
    //Clear Proc 
    $("#layoutDiv").empty();
    $("#defectDiv").empty();
  };

  //prd_seq_id 回车时间 调用F5？还是F8？
  $("#prdSeqIdTxt").keypress(function(event){
    if(event.keyCode==13){
        f5_func();
    }
  })
  $("#f1_btn").click(f1_func);
  $("#f2_btn").click(function(){
    //测试
    showErrorDialog("errorCode","出错了");
  })
  $("#f5_btn").click(f5_func);
  $("#f8_btn").click(f8_func);

  $("#f9_btn").click(function(){
      $("#selectWorderBtn").showSelectWorderDialog({
          wo_type    : "W",
          callbackFn : function(data) {
              f1_func(data.wo_id);
        }
      })  
  })

  $("#f10_test_btn").click(function(){
    $("#f10_test_btn").showKeyBoardDialog({
          // wo_type    : "W",
          callbackFn : function(data) {
              alert(data.keyInResult);
        }
    })
  })
   
   // showSuccessDialog2
  
});